<?php
namespace EasySwoole\EasySwoole;

use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Socket\Dispatcher;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Db\Config;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\Utility\File;
use EasySwoole\Component\Di;
use EasySwoole\Session\Session;
use EasySwoole\Session\SessionFileHandler;
use EasySwoole\EasySwoole\Crontab\Crontab;

use App\WebSocket\WebSocketEvent;
use App\WebSocket\WebSocketParser;

use App\Storage\ClientStore;
use App\Storage\UserStore;
use App\Storage\OnlineClient;
use App\Storage\OnlineUser;

use App\Task\CheckHeartbeatTask;

use App\Utility\Ccid;

class EasySwooleEvent implements Event
{
    public static function initialize()
    {
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');
    }

    public static function mainServerCreate(EventRegister $register)
    {
        //****实例化终端和网页用户以及流水号*****
        ClientStore::getInstance();
        OnlineClient::getInstance();
        // UserStore::getInstance();
        OnlineUser::getInstance();
        Ccid::getInstance();
        //****实例化终端和网页用户以及流水号*****

        // ***************开始定时任务*************
        // 检查心跳
        Crontab::getInstance()->addTask(CheckHeartbeatTask::class);
        // ***************开始定时任务*************

        //**************** session *****************
        // 自定义 session handler
        $handler = new SessionFileHandler(EASYSWOOLE_TEMP_DIR);
        // 指定 cookie name, save path
        Session::getInstance($handler, 'easysession', dirname(__FILE__) . DIRECTORY_SEPARATOR . 'session' . DIRECTORY_SEPARATOR . 'session.php');
        //**************** session *****************

        //************ websocket控制器 ***********
        // 注册服务事件
        $register->add(EventRegister::onOpen, [WebSocketEvent::class, 'onOpen']);
        $register->add(EventRegister::onClose, [WebSocketEvent::class, 'onClose']);
        
        $conf = new \EasySwoole\Socket\Config();
        // 设置WebSocket 模式
        $conf->setType(\EasySwoole\Socket\Config::WEB_SOCKET);
        // 设置解析器
        $conf->setParser(new WebSocketParser());
        // 创建 Dispatcher 对象 并注入 config
        $dispatch = new Dispatcher($conf);
        //  处理接收到的消息
        $register->set(EventRegister::onMessage, function (\swoole_websocket_server $server, \swoole_websocket_frame $frame) use ($dispatch) {
            $dispatch->dispatch($server, $frame->data, $frame);
        });
        //************ websocket控制器 ***********
         
        //*************** 数据库配置***************
        $config = new Config();
        $config->setDatabase('');
        $config->setUser('');
        $config->setPassword('');
        $config->setHost('');
        $config->setPort();
        DbManager::getInstance()->addConnection(new Connection($config));
        //*************** 数据库配置***************

        // ********全局异常和错误打印日志*********
        $errorHandler = Di::getInstance()->get(SysConst::ERROR_HANDLER);
        if (!is_callable($errorHandler)) {
            $errorHandler = function ($errorCode, $description, $file = null, $line = null) {
                if ($file != null && $line != null) {
                    $content = '在文件 "' . $file . '" 的第 ' . $line . ' 行出现错误 : "' . $description . '" 错误码: ' . $errorCode;
                } else {
                    $content = '出现错误 : "' . $description . '" 错误码: ' . $errorCode;
                }
                Logger::getInstance()->log($content, Logger::LOG_LEVEL_ERROR, 'RECORD');
            };
        }
        set_error_handler($errorHandler);
        // ********全局异常和错误打印日志*********
    }

    public static function onRequest(Request $request, Response $response): bool
    {
        // TODO: Implement onRequest() method.
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
        // TODO: Implement afterAction() method.
    }
}
